package com.sencorsta.ids.robot.userSimulation;


import com.alibaba.fastjson.JSONObject;
import com.sencorsta.ids.common.information.ErrorCodeList;
import com.sencorsta.ids.common.service.RedisService;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.http.HttpHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
* @description: 机器人加入-指定游戏房间
* @author TAO
* @date 2019/12/5 20:50
*/
public class SimulationJoinRoom extends HttpHandler implements RedisService {
    @Override
    public String doPost(ChannelHandlerContext ctx, FullHttpRequest request, JSONObject params) {
        Out.debug("--------------------机器人加入-指定游戏房间-----SimulationJoinRoom--------------------");

        int gameId=params.getInteger("gameId");
        int roomId=params.getInteger("roomId");
        int count=params.getInteger("count");
        //可用的机器人set
        Set<GameSimUser> usableSimUser=new HashSet<>();
        for (var simulation: SimulationCenter.simulationUserMap.keySet()){
            GameSimUser gameSimUser=(GameSimUser)SimulationCenter.simulationUserMap.get(simulation);
            if (!gameSimUser.isInRoom&&gameSimUser.isOnline){
                usableSimUser.add(gameSimUser);//得到可用的机器人
            }
        }

        if (usableSimUser.size()==0){
            return error(ErrorCodeList.NOT_USABLE_SIMULATION);
        }
        if (usableSimUser.size()<count){
            return error(ErrorCodeList.USABLE_SIMULATION_INSUFFICIENT);
        }

        Iterator<GameSimUser> it = usableSimUser.iterator();
        while (it.hasNext()){
            if (count>0){
                it.next().joinRoom(gameId,roomId);
                it.remove();//将当前添加的机器人在可用机器人set中移除
                count--;
            }else{
                break;
            }
        }
        return success();
    }

    @Override
    public String doGet(ChannelHandlerContext ctx, FullHttpRequest request, JSONObject params) {
        return doPost(ctx, request, params);
    }

    @Override
    public String getPath() {
        return "/Robot/SimulationJoinRoom";
    }
}
